package com.gdth.service;

import com.gdth.bank.BankApplication;
import com.gdth.thread.SynchronizeThread;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;
import android.util.Log;

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class KeepLiveJobService extends JobService{

	@Override
	public boolean onStartJob(JobParameters params) {
	
		 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			 	start();
			 	Log.i("__________", "_________KeepLiveJobService___Start");
	            jobFinished(params, true);
	            startSever();
	        } else {
	        	start();
	        
	            jobFinished(params , false);
	            startSever();
	        }
		
		return false;
	}

	SynchronizeThread thread = new SynchronizeThread();
    
	private void start() {
//		startHeart();
//		new Thread(networdThread).start();
		
		if(!thread.isAlive()) {
			if (thread != null) {
				thread = new SynchronizeThread();
			}
			thread.start();
		}
	}
	@Override
	public boolean onStopJob(JobParameters params) {
		Log.i("__________", "_________KeepLiveJobService___stop");
		return false;
	}
	
	public void startSever() {
		JobScheduler scheduler =  (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
		ComponentName componentName =  new ComponentName(BankApplication.mInstance.getBaseContext(), KeepLiveJobService.class);
		JobInfo.Builder builder =new  JobInfo.Builder(1, componentName);
        if (Build.VERSION.SDK_INT >= 24) {
            builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS); //执行的最小延迟时间
            builder.setOverrideDeadline(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);  //执行的最长延时时间
            builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);
            builder.setBackoffCriteria(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS, JobInfo.BACKOFF_POLICY_LINEAR);//线性重试方案
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                builder.setPeriodic(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);
            }
        }
        builder.setPersisted(true);  // 设置设备重启时，执行该任务
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
        builder.setRequiresCharging(true); // 当插入充电器，执行该任务
        JobInfo  info = builder.build();
        scheduler.schedule(info); //开始定时执行该系统任务
	}

}
